package com.xingkeduo.delayQueue.service;

import com.alibaba.fastjson.JSON;
import com.rabbitmq.client.Channel;
import com.xingkeduo.delayQueue.model.TaskModel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.UUID;

import static com.xingkeduo.config.RabbitMQConfig.*;

/**
 * @author chi  2019-02-22 15:41
 **/

@Component
@Slf4j
public class RabbitMqPluginTaskService implements TaskService {

    @Resource
    private RabbitTemplate rabbitTemplate;




    @Override
    public void addToDeplayQueue(TaskModel task) {
        this.rabbitTemplate.convertAndSend(DELAYED_EXCHANGE_XDELAY, DELAY_ROUTING_KEY_XDELAY, task, new MessagePostProcessor() {
            @Override
            public Message postProcessMessage(Message message) throws AmqpException {

                int expireTime = task.getExpireTime();
                if(expireTime>0){
                    message.getMessageProperties().setDelay(expireTime);
                }else {
                    message.getMessageProperties().setDelay((int)task.getTaskModelEnum().getExpireTime());
                }
                return message;
            }
        }, new CorrelationData(UUID.randomUUID().toString()));
    }

    @Override
    public boolean removeFromDeplayQueue(TaskModel task) {
        return false;
    }

    @RabbitListener(queues = IMMEDIATE_QUEUE_XDELAY)
    public void transferFromDelayQueue(@Payload String sendMessage, Channel channel, Message message) {

        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (IOException e) {
            log.error("basicAck 发生异常； ", e);
        }

        try {
            String s = new String(message.getBody(), StandardCharsets.UTF_8);
            log.info("消费者监听交易记录信息:{}", s);
            TaskModel taskModel = JSON.parseObject(s, TaskModel.class);
            addToTaskQue(taskModel.getId(), taskModel.getTaskModelEnum().toString());
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            log.error("消息体解析 发生异常； ", e.fillInStackTrace());
        }

    }
}
